package com.web.security;

import com.service.serviceImpl.UserDetailServiceImpl;
import com.web.security.filter.IgnoreUrlList;
import com.web.security.filter.JwtAuthenticationTokenFilter;
import com.web.security.handler.AccessDeniedHandler;
import com.web.security.handler.NoAuthenricationHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author liuxuhuang
 * @date 2023年03月30日 20:32
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    @Qualifier(value = "userDetailServiceImpl")
    private UserDetailServiceImpl userDetailService;
    @Resource
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Resource
    private NoAuthenricationHandler noAuthenricationHandler;
    @Resource
    private AccessDeniedHandler accessDeniedHandler;

    @Resource
    private IgnoreUrlList ignoreUrlList;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        List<String> urls = ignoreUrlList.getUrl();
        http.headers().frameOptions().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.cors().and().csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.authorizeRequests();
        for (String url : urls) {
            registry.antMatchers(url).permitAll();
        }
        registry
                .antMatchers("/student/**").hasRole("student")
                .antMatchers("/dorm/**").hasRole("student")
                .antMatchers("/student2/**").hasRole("student")
                .antMatchers("/student3/**").hasRole("student")
                .antMatchers("/auth/user/info").hasAnyRole("student", "dormManagement", "schoolManagement", "plumber", "guest")
                .anyRequest().authenticated();
        http.formLogin().and()
                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                .exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler)
                .authenticationEntryPoint(noAuthenricationHandler)
        ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
